<template>
	<view class="content">
		<z-paging ref="pagingRef" v-if="firstLoaded || isCurrentPage" v-model="dataList" @query="queryList"
			:fixed="false">
			<view class="item" v-for="(item, index) in dataList" :key="index" @click="itemClick(item)">
				<view class="uni-flex uni-align-center top">
					<image :src="item.avatar===null||item.avatar===''?`${$ImgBaseUrl}banner.png`:item.avatar"
						class="photo" />
					<view class="uni-flex-column center">
						<text class="title">{{item?.name}}</text>
						<text class="distance">距您{{item?.distance}}km</text>
					</view>
					<view class="uni-flex-column uni-align-center">
						<text
							:class="item.closeRate<=30?'num-red':item.closeRate<=60?'num-orange':'num'">{{item.closeRate}}%</text>
						<text class="text">结单率</text>
					</view>
				</view>
				<text v-for="(item, index) in item.labelNames" :key="index" class="project">
					{{ item }}
				</text>
				<!-- 服务地址添加点击事件 -->
				<view class="box" @click.stop="openMap(item)">
					<text class="text1">服务地址：</text>
					<text class="text2">{{item?.address}}</text>
				</view>
				<view class="uni-flex box">
					<view class="left">
						<text class="text1">发布时间：</text>
						<text class="text2">{{item?.createTime.slice(0,10)}}</text>
					</view>
					<text class="text3" v-if="item?.isBrowse===true">浏览过</text>
				</view>
			</view>
			<template #empty>
				<view class="empty-container">
					<view class="empty-content">暂无数据</view>
				</view>
			</template>
		</z-paging>
	</view>
</template>
<script setup>
	import {
		ref,
		watch,
		nextTick,
		reactive,
		onMounted,
		onUnmounted
	} from "vue";
	import {
		queryJobList
	} from "@/api/findJob.js";
	import {
		getCityCode,
		getLatitude,
		getLongitude
	} from "@/common/util.js";
	const props = defineProps({
		tabIndex: {
			type: Number,
			default: 0
		},
		currentIndex: {
			type: Number,
			default: 0
		},
		currentId: {
			type: Number,
			default: 0
		},
		filterParams: {
			type: Object,
			default: () => ({})
		}
	});

	const emit = defineEmits(["reload"]);
	const dataList = ref([]);
	const firstLoaded = ref(false);
	const isCurrentPage = ref(false);
	const pagingRef = ref(null);
	const state = reactive({
		currentAreaId: "" // 存储选中的区域ID
	});

	// 打开地图导航
	const openMap = (item) => {
		console.log('item', item);
		// 检查是否有经纬度信息
		if (item.lat && item.lng) {
			// 使用微信小程序地图接口
			uni.openLocation({
				latitude: Number(item.lat), // 目标纬度
				longitude: Number(item.lng), // 目标经度
				// name: item.name, // 位置名称
				address: item.address, // 详细地址
				scale: 12, // 缩放级别，范围5-18
				success: () => {
					console.log('地图打开成功');
				},
				fail: (err) => {
					console.error('地图打开失败：', err);
					uni.showToast({
						title: '无法打开地图',
						icon: 'none'
					});
				}
			});
		} else {
			// 如果没有经纬度，尝试使用地址解析
			uni.showToast({
				title: '正在解析地址...',
				icon: 'loading'
			});

			// 调用逆地理编码接口（需要后端支持）
			uni.request({
				url: '/api/geo/address-to-coord',
				method: 'GET',
				data: {
					address: item.address
				},
				success: (res) => {
					if (res.data.success && res.data.latitude && res.data.longitude) {
						uni.openLocation({
							latitude: Number(res.data.latitude),
							longitude: Number(res.data.longitude),
							name: item.name,
							address: item.address,
							scale: 18
						});
					} else {
						uni.showToast({
							title: '无法解析该地址',
							icon: 'none'
						});
					}
				},
				fail: () => {
					uni.showToast({
						title: '地址解析失败',
						icon: 'none'
					});
				}
			});
		}
	};

	const handleAreaChange = async (data) => {
		if (!data?.areaId) {
			console.error('未获取到有效的areaId:', data);
			return;
		}
		state.currentAreaId = data.areaId;
		console.log('人员列表接收的areaId:', state.currentAreaId);

		if (pagingRef.value) {
			await nextTick();
			pagingRef.value.reload();
		} else {
			setTimeout(async () => {
				await nextTick();
				pagingRef.value?.reload();
			}, 500);
		}
	};

	watch(() => props.currentIndex, (newVal) => {
		if (newVal === props.tabIndex && !firstLoaded.value) {
			nextTick(() => {
				setTimeout(() => {
					isCurrentPage.value = true;
				}, 100);
			});
		}
	}, {
		immediate: true
	});

	const reload = () => {
		nextTick(() => {
			pagingRef.value?.reload();
		});
	};
	defineExpose({
		reload
	});

	const queryList = async (pageNum, pageSize) => {
		try {
			const params = {
				pageNum: pageNum,
				pageSize,
				cityCode: state.currentAreaId || getCityCode(),
				categoryId: props.currentId,
				lat: getLatitude(),
				lng: getLongitude(),
				// 添加筛选参数
				// ...props.filterParams
			};
			// 从 filterParams 中获取用户选择的 [min, max] 数组
			if (props.filterParams.nearDistance && props.filterParams.nearDistance.length === 2) {
				params.nearDistanceMin = props.filterParams.nearDistance[0]; // 最小距离
				params.nearDistanceMax = props.filterParams.nearDistance[1]; // 最大距离
			}

			// 处理搜索关键词
			if (props.filterParams.jobName) {
				params.jobName = props.filterParams.jobName;
			}

			// 处理服务项筛选（关键修改）
			if (props.filterParams.serviceItem) {
				params.serviceItem = props.filterParams.serviceItem; // 直接传递逗号分隔的字符串
			}
			// 添加结算相关参数（关键修改）
			if (props.filterParams.closeQuickly !== undefined) {
				params.closeQuickly = props.filterParams.closeQuickly;
			}
			if (props.filterParams.closeRateMax !== undefined) {
				params.closeRateMax = props.filterParams.closeRateMax;
			}
			console.log('params',params);

			const res = await queryJobList(params);

			const listData = Array.isArray(res) ? res : (res.rows || []);
			if (!Array.isArray(listData)) {
				throw new Error(`接口返回数据格式错误，预期数组，实际: ${typeof listData}`);
			}

			pagingRef.value.complete(listData);
			firstLoaded.value = true;

		} catch (error) {
			console.error('queryPeopleList请求失败:', error.message);
			pagingRef.value.complete(false);
		}
	};

	onMounted(() => {
		uni.$off('areaSelected', handleAreaChange);
		uni.$on('areaSelected', handleAreaChange);
	});

	onUnmounted(() => {
		uni.$off('areaSelected', handleAreaChange);
	});

	const itemClick = (item) => {
		uni.navigateTo({
			url: '/pages/tabBars/findJob/jobDetail?jobId=' + item.id,
		});
	};
</script>
<style lang="scss" scoped>
	.content {
		height: calc(100vh - 200rpx);
	}

	.item {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 30rpx 20rpx;
		margin: 26rpx 24rpx 0;

		.top {
			padding-bottom: 18rpx;
			border-bottom: 1rpx solid #ededed;
			margin-bottom: 18rpx;

			.photo {
				width: 88rpx;
				height: 88rpx;
				border-radius: 50%;
				margin-right: 24rpx;
			}

			.center {
				flex: 1;
			}

			.title {
				font-size: 28rpx;
				font-weight: 500;
				color: #333333;
				margin-bottom: 12rpx;
			}

			.distance {
				font-size: 24rpx;
				color: #666666;
			}

			.num {
				font-size: 36rpx;
				font-weight: bold;
				color: #6bc98d;
				font-weight: 500;
				margin-bottom: 10rpx;
			}

			.num-red {
				font-weight: 500;
				font-size: 36rpx;
				color: #FF6A47;
			}

			.num-orange {
				font-weight: 500;
				font-size: 36rpx;
				color: #FEB310;
			}

			.text {
				font-size: 22rpx;
				color: #999999;
			}
		}

		.project {
			color: #2f80ed;
			font-size: 24rpx;
			font-weight: 500;
			background: #e6f1ff;
			padding: 6rpx 10rpx;
			margin-right: 14rpx;
			border-radius: 4rpx;
		}

		.box {
			font-size: 24rpx;
			margin-top: 16rpx;

			// 地址可点击样式
			&:nth-child(3) {
				cursor: pointer;

				// .text2 {
				// 	text-decoration: underline;
				// 	color: #2f80ed;
				// }
			}

			.text1 {
				color: #999999;
			}

			.text2 {
				color: #333333;
			}

			.text3 {
				color: #2F80ED;
			}

			.left {
				flex: 1;
			}
		}
	}

	.empty-container {
		min-height: 120rpx;
		width: 100%;
		display: flex;
		justify-content: center;
	}
</style>